<?php
/**
 * @author       Sixe Team
 * @email        info@eee-eee.com
 * @url          http://www.eee-eee.com
 * @copyright    Copyright (C) 2010 - 2019 Sixe Information Technology Limited. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @date         2019/10/01 10:00
 */

defined('JPATH_PLATFORM') or die;

use Joomla\Utilities\ArrayHelper;


JFormHelper::loadFieldClass('list');
JLoader::register('JFormFieldCategoryEdit', JPATH_ADMINISTRATOR . '/components/com_categories/models/fields/categoryedit.php');

/**
 * Field to load a dropdown list of available user groups
 *
 * @since  3.2
 */
class JFormFieldCategoryFlow extends JFormFieldCategoryEdit
{
	/**
	 * The form field type.
	 *
	 * @var        string
	 * @since   3.2
	 */
	public $type = 'CategoryFlow';

	/**
	 * Method to attach a JForm object to the field.
	 *
	 * @param   \SimpleXMLElement $element The SimpleXMLElement object representing the `<field>` tag for the form field object.
	 * @param   mixed $value The form field value to validate.
	 * @param   string $group The field name group control value. This acts as an array container for the field.
	 *                                       For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                       full field name would end up being "bar[foo]".
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.7.0
	 */
	public function setup(SimpleXMLElement $element, $value, $group = null)
	{
		return parent::setup($element, $value, $group);
	}

	/**
	 * Method to get the options to populate list
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.2
	 */
	protected function getOptions()
	{
		$app = JFactory::getApplication();
		$option = $app->input->getCmd('option', '');
		$view = $app->input->getCmd('view', '');
		$id = $app->input->getInt('id', 0);
		$options = parent::getOptions();
		$user = JFactory::getUser();

		// Let's get the id for the current item, either category or content item.
		$db = JFactory::getDbo();
		$groups = implode(',', $user->groups);

		$query = $db->getQuery(true)
			->select("DISTINCT a.category_id")
			->from('#__workflow_categories AS a');
		if ($option == 'com_sixeworkflow' && $view == 'workflow' && $id > 0) {
			$query->where('a.workflow_id !=' . $id);
		}
		// Get the options.
		$db->setQuery($query);
		try {
			$catids = $db->loadColumn();

		} catch (RuntimeException $e) {
			JError::raiseWarning(500, $e->getMessage());
		}


		foreach ($options as $key => $co) {
			if (in_array($co->value, $catids)) {
				unset($options[$key]);
			}
		}

		return $options;
	}


	protected function getInput()
	{
		$options = $this->getOptions();

		if (count($options)) {
			return parent::getInput();
		} else {
			return '<input type="text" readonly="true" placeholder="' . JText::_('JGLOBAL_TYPE_OR_SELECT_CATEGORY') . '" />';
		}
	}

}
